package com.edu.controller;

import com.R;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.edu.exceptionhandler.MyException;
import com.edu.service.VodService;
import com.edu.utils.ConstantVodUtils;
import com.edu.utils.InitVodClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.RequestWrapper;
import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

	@Autowired
	private VodService vodService;

	//上传视频到阿里云
	@PostMapping("/uploadAlyVideo")
	public R uploadAlyVideo(MultipartFile file){

		String videoId = vodService.uploadVideoAly(file);
		return R.ok().data("videoId",videoId);
	}

	@DeleteMapping("/removeAlyVideo/{id}")
	public R removeAlyVideo(@PathVariable String id){

		try {
			//初始化对象
			DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);

			//创建删除视频request对象
			DeleteVideoRequest request = new DeleteVideoRequest();
			request.setVideoIds(id);

			//调用初始化对象来实现删除
			client.getAcsResponse(request);

			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			throw new MyException(20001,"删除视频失败");
		}

	}

	//删除多个阿里云视频的方法
	//参数删除多个视频id List videoIdList
	@DeleteMapping("/delete-batch")
	public R deleteBatch(@RequestParam("videoIdList") List<String> videoIdList){

		vodService.removeMoreAlyVideo(videoIdList);
		return R.ok();
	}

	@GetMapping("/getPlayAuth/{id}")
	public R getPlayAuth(@PathVariable String id){

		try {
			DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
			GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();

			request.setVideoId(id);
			request.getVideoId();
			GetVideoPlayAuthResponse response = client.getAcsResponse(request);
			String playAuth = response.getPlayAuth();

			return R.ok().data("playAuth",playAuth);
		} catch (ClientException e) {
			e.printStackTrace();
			throw new MyException(20001,"获取凭证失败");
		}

	}
}
